<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="UTF-8">
  <meta 
    name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <meta 
    http-equiv="X-UA-Compatible" 
    content="ie=edge">
  <meta 
    name="theme-color" 
    content="#fff" 
    id="theme-color">
  <meta 
    name="description" 
    content="hexoDemo用于介绍如何使用hexo">
  <link 
    rel="icon" 
    href="/">
  <title>05-Node.js内置模块：fs文件模块</title>
  
    
      <meta 
        property="og:title" 
        content="05-Node.js内置模块：fs文件模块">
    
    
      <meta 
        property="og:url" 
        content="https://zwl5670.gitee.io/2011/08/01/11-Node.js/05-Node.js%E5%86%85%E7%BD%AE%E6%A8%A1%E5%9D%97%EF%BC%9Afs%E6%96%87%E4%BB%B6%E6%A8%A1%E5%9D%97/index.html">
    
    
      <meta 
        property="og:img" 
        content="https://img.songhn.com/img/Y67gdd.png">
    
    
      <meta 
        property="og:img" 
        content="hexoDemo用于介绍如何使用hexo">
    
    
      <meta 
        property="og:type" 
        content="article">
      <meta 
        property="og:article:published_time" 
        content="2011-08-01">
      <meta 
        property="og:article:modified_time" 
        content="2023-03-14">
      <meta 
        property="og:article:author" 
        content="zwl5670">
      
        
          <meta 
            property="og:article:tag" 
            content="Node">
        
      
    
  
  
  <link rel="preload" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css" as="style" >
  <link rel="preload" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css" as="style" >
  <link rel="preload" href="/css/main.css" as="style" >
  
  <link rel="modulepreload" href="//instant.page/5.1.0">
  
  <link rel="stylesheet" href="/css/main.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css">
  
  
  
    <link rel="stylesheet" href="/js/lib/lightbox/baguetteBox.min.css">
  
  <script>
    function loadScript(url, cb) {
      var script = document.createElement('script');
      script.src = url;
      if (cb) script.onload = cb;
      script.async = true;
      document.body.appendChild(script);
    }
    function loadCSS(href, data, attr) {
      var sheet = document.createElement('link');
      sheet.ref = 'stylesheet';
      sheet.href = href;
      sheet.dataset[data] = attr;
      document.head.appendChild(sheet);
    }
    function changeCSS(cssFile, data, attr) {
      var oldlink = document.querySelector(data);
      var newlink = document.createElement("link");
      newlink.setAttribute("rel", "stylesheet");
      newlink.setAttribute("href", cssFile);
      newlink.dataset.prism = attr;
      document.head.replaceChild(newlink, oldlink);
    }
  </script>
  
    
  
  <script>
    // control reverse button
    var reverseDarkList = {
      dark: 'light',
      light: 'dark'
    };
    var themeColor = {
      dark: '#1c1c1e',
      light: '#fff'
    }
    // get the data of css prefers-color-scheme
    var getCssMediaQuery = function() {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };
    // reverse current darkmode setting function
    var reverseDarkModeSetting = function() {
      var setting = localStorage.getItem('user-color-scheme');
      if(reverseDarkList[setting]) {
        setting = reverseDarkList[setting];
      } else if(setting === null) {
        setting = reverseDarkList[getCssMediaQuery()];
      } else {
        return;
      }
      localStorage.setItem('user-color-scheme', setting);
      return setting;
    };
    // apply current darkmode setting
  </script>
  
    <script>
      var setDarkmode = function(mode) {
      var setting = mode || localStorage.getItem('user-color-scheme');
      if(setting === getCssMediaQuery()) {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else if(reverseDarkList[setting]) {
        document.documentElement.setAttribute('data-user-color-scheme', setting);
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[getCssMediaQuery()];
        document.getElementById('theme-color').dataset.mode = getCssMediaQuery();
      }
    };
    setDarkmode();
    </script>
  
  
  
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.js" as="script">
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.css" as="style" >
  
  
    <link rel="preload" href="/js/lib/lozad.min.js" as="script">
  
  
  
  
  
  
<meta name="generator" content="Hexo 6.3.0"></head>

  <body>
    <div class="wrapper">
       
      <nav class="navbar">
  <div class="navbar-logo">
    <a class="navbar-logo-main" href="/">
      
      <span class="navbar-logo-dsc">前端面试</span>
      </a>
  </div>
  <div class="navbar-menu">
    
      <a 
        href="/" 
        class="navbar-menu-item">
        
          首页
        
      </a>
    
      <a 
        href="/archives" 
        class="navbar-menu-item">
        
          归档
        
      </a>
    
      <a 
        href="/tags" 
        class="navbar-menu-item">
        
          标签
        
      </a>
    
      <a 
        href="/categories" 
        class="navbar-menu-item">
        
          分类
        
      </a>
    
      <a 
        href="/about" 
        class="navbar-menu-item">
        
          关于
        
      </a>
    
      <a 
        href="/links" 
        class="navbar-menu-item">
        
          友链
        
      </a>
    
    <button 
      class="navbar-menu-item darknavbar navbar-menu-btn" 
      aria-label="Toggle dark mode"
      id="dark">
      <i class="iconfont icon-weather"></i>
    </button>
    <button 
      class="navbar-menu-item searchnavbar navbar-menu-btn" 
      aria-label="Toggle search"
      id="search">
      <!-- <i 
        class="iconfont icon-search" 
        style="font-size: 1.2rem; font-weight: 400;">
      </i> -->
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img"
        class="iconify iconify--ion" width="28" height="28" preserveAspectRatio="xMidYMid meet" viewBox="0 0 512 512">
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M256 80a176 176 0 1 0 176 176A176 176 0 0 0 256 80Z"></path>
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M232 160a72 72 0 1 0 72 72a72 72 0 0 0-72-72Z"></path>
        <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="28"
          d="M283.64 283.64L336 336"></path>
      </svg>
    </button>
  </div>
</nav> 
      
      <div 
        id="local-search" 
        style="display: none">
        <input
          class="navbar-menu-item"
          id="search-input"
          placeholder="请输入搜索内容..." />
        <div id="search-content"></div>
      </div>
      
      <div class="section-wrap">
        <div class="container">
          <div class="columns">
            <aside class="left-column">
              
              <div class="card card-author">
                
  <img 
    src="https://img.songhn.com/img/Y67gdd.png" 
    class="author-img"
    width="88"
    height="88"
    alt="author avatar">

<p class="author-name">zwl5670</p>
<p class="author-description">前端学习资料</p>
<div class="author-message">
  <a 
    class="author-posts-count" 
    href="/archives">
    <span>215</span>
    <span>文章</span>
  </a>
  <a 
    class="author-categories-count" 
    href="/categories">
    <span>14</span>
    <span>分类</span>
  </a>
  <a 
    class="author-tags-count" 
    href="/tags">
    <span>14</span>
    <span>标签</span>
  </a>
</div>

              </div>
               <div class="sticky-tablet">
  
  
    <article class="display-when-two-columns spacer">
      <div class="card card-content toc-card">
        <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Node-js-%E7%9A%84%E5%AE%98%E6%96%B9API%E6%96%87%E6%A1%A3"><span class="toc-text">Node.js 的官方API文档</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Node-js-%E4%B8%AD%E6%A8%A1%E5%9D%97%E7%9A%84%E5%88%86%E7%B1%BB"><span class="toc-text">Node.js 中模块的分类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%86%85%E7%BD%AE%E6%A8%A1%E5%9D%97"><span class="toc-text">1、内置模块</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81require-%E5%8A%A0%E8%BD%BD%E7%AC%AC%E4%B8%89%E6%96%B9%E5%8C%85%E7%9A%84%E6%9C%BA%E5%88%B6"><span class="toc-text">2、require 加载第三方包的机制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E6%A8%A1%E5%9D%97%EF%BC%88module%EF%BC%89%EF%BC%9A"><span class="toc-text">3、自定义模块（module）：</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6"><span class="toc-text">读取文件</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6-fs-readFile"><span class="toc-text">异步读取文件 fs.readFile()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#promise-%E5%B0%81%E8%A3%85-fs-readFile"><span class="toc-text">promise 封装 fs.readFile()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#async-%E2%80%A6-await-%E5%B0%81%E8%A3%85-fs-readFile"><span class="toc-text">async … await 封装 fs.readFile()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6-fs-readFileSync"><span class="toc-text">同步读取文件 fs.readFileSync()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Node-js-%E4%B8%AD%E7%9A%84%E5%90%8C%E6%AD%A5%E5%92%8C%E5%BC%82%E6%AD%A5%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-text">Node.js 中的同步和异步的区别</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%99%E5%85%A5%E6%96%87%E4%BB%B6"><span class="toc-text">写入文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E6%96%87%E4%BB%B6"><span class="toc-text">删除文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Buffer"><span class="toc-text">Buffer</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%BB%E5%8F%96%E7%9B%AE%E5%BD%95"><span class="toc-text">读取目录</span></a></li></ol>
      </div>
    </article>
  
  
  <article class="card card-content categories-widget">
    <div class="categories-card">
  <div class="categories-header">
    <i 
      class="iconfont icon-fenlei" 
      style="padding-right: 2px;">
    </i>分类
  </div>
  <div class="categories-list">
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/">
        <div class="categories-list-item">
          前端工具
          <span class="categories-list-item-badge">13</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          CSS基础
          <span class="categories-list-item-badge">18</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          CSS进阶
          <span class="categories-list-item-badge">9</span>
        </div>
      </a>
    
      <a href="/categories/HTML/">
        <div class="categories-list-item">
          HTML
          <span class="categories-list-item-badge">12</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          JS基础
          <span class="categories-list-item-badge">56</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80ES6/">
        <div class="categories-list-item">
          JS基础ES6
          <span class="categories-list-item-badge">10</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/">
        <div class="categories-list-item">
          JS基础异步
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/JS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          JS进阶
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/%E7%A7%BB%E5%8A%A8web/">
        <div class="categories-list-item">
          移动web
          <span class="categories-list-item-badge">3</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%92%8CDOM/">
        <div class="categories-list-item">
          CSS和DOM
          <span class="categories-list-item-badge">6</span>
        </div>
      </a>
    
      <a href="/categories/Node/">
        <div class="categories-list-item">
          Node
          <span class="categories-list-item-badge">16</span>
        </div>
      </a>
    
      <a href="/categories/Vue%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          Vue基础
          <span class="categories-list-item-badge">15</span>
        </div>
      </a>
    
      <a href="/categories/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">
        <div class="categories-list-item">
          性能优化
          <span class="categories-list-item-badge">7</span>
        </div>
      </a>
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/">
        <div class="categories-list-item">
          前端工程化
          <span class="categories-list-item-badge">8</span>
        </div>
      </a>
    
  </div>
</div>
  </article>
  
  <article class="card card-content tags-widget">
    <div class="tags-card">
  <div class="tags-header">
    <i 
      class="iconfont icon-biaoqian" 
      style="padding-right: 2px;">
    </i>热门标签
  </div>
  <div class="tags-list">
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80/" 
        title="JS基础">
        <div class="tags-list-item">JS基础</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%9F%BA%E7%A1%80/" 
        title="CSS基础">
        <div class="tags-list-item">CSS基础</div>
      </a>
    
      <a 
        href="/tags/Node/" 
        title="Node">
        <div class="tags-list-item">Node</div>
      </a>
    
      <a 
        href="/tags/Vue%E5%9F%BA%E7%A1%80/" 
        title="Vue基础">
        <div class="tags-list-item">Vue基础</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/" 
        title="前端工具">
        <div class="tags-list-item">前端工具</div>
      </a>
    
      <a 
        href="/tags/HTML/" 
        title="HTML">
        <div class="tags-list-item">HTML</div>
      </a>
    
      <a 
        href="/tags/JS%E8%BF%9B%E9%98%B6/" 
        title="JS进阶">
        <div class="tags-list-item">JS进阶</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
        title="JS基础异步">
        <div class="tags-list-item">JS基础异步</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80ES6/" 
        title="JS基础ES6">
        <div class="tags-list-item">JS基础ES6</div>
      </a>
    
      <a 
        href="/tags/CSS%E8%BF%9B%E9%98%B6/" 
        title="CSS进阶">
        <div class="tags-list-item">CSS进阶</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/" 
        title="前端工程化">
        <div class="tags-list-item">前端工程化</div>
      </a>
    
      <a 
        href="/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" 
        title="性能优化">
        <div class="tags-list-item">性能优化</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%92%8CDOM/" 
        title="CSS和DOM">
        <div class="tags-list-item">CSS和DOM</div>
      </a>
    
      <a 
        href="/tags/%E7%A7%BB%E5%8A%A8web/" 
        title="移动web">
        <div class="tags-list-item">移动web</div>
      </a>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
            <main class="main-column">
              
<article class="card card-content">
  <header>
    <h1 class="post-title">
      05-Node.js内置模块：fs文件模块
    </h1>
  </header>
  <div class="post-meta post-show-meta">
    <time datetime="2011-07-31T16:00:00.000Z">
      <i 
        class="iconfont icon-calendar" 
        style="margin-right: 2px;">
      </i>
      <span>2011-08-01</span>
    </time>
    
      <span class="dot"></span>
      
        <a 
          href="/categories/Node/" 
          class="post-meta-link">
          Node
        </a>
      
    
    
      <span class="dot"></span>
      <span>1.9k 字</span>
    
  </div>
  
    <div 
      class="post-meta post-show-meta" 
      style="margin-top: -10px;">
      <div style="display: flex; align-items: center;">
        <i 
          class="iconfont icon-biaoqian" 
          style="margin-right: 2px; font-size: 1.15rem;">
        </i>
        
          
          <a 
            href="/tags/Node/" 
            class="post-meta-link">
            Node
          </a>
        
      </div>
    </div>
  
  </header>
  <div 
    id="section" 
    class="post-content">
    <p><ArticleTopAd></ArticleTopAd></p>
<h2 id="Node-js-的官方API文档"><a href="#Node-js-的官方API文档" class="headerlink" title="Node.js 的官方API文档"></a>Node.js 的官方API文档</h2><ul>
<li><p>Node.js 的API文档（英文）： <a target="_blank" rel="noopener" href="https://nodejs.org/docs/latest-v8.x/api/index.html">https://nodejs.org/docs/latest-v8.x/api/index.html</a></p>
</li>
<li><p>Node.js 的API文档（中文）：<a target="_blank" rel="noopener" href="http://nodejs.cn/api/">http://nodejs.cn/api/</a></p>
</li>
</ul>
<p>关于 Node.js 的内置模块和常见API，可以看官方文档。</p>
<p>查阅文档时，稳定指数如下：</p>
<ul>
<li><p>红色：废弃。</p>
</li>
<li><p>橙色：实验。表示当前版本可用，其他版本不确定。也许不向下兼容，建议不要在生产环境中使用该特性。</p>
</li>
<li><p>绿色：稳定。与 npm 生态系统的兼容性是最高的优先级。</p>
</li>
</ul>
<h2 id="Node-js-中模块的分类"><a href="#Node-js-中模块的分类" class="headerlink" title="Node.js 中模块的分类"></a>Node.js 中模块的分类</h2><p>Node.js 应用由模块组成，采用 CommonJS 模块规范。Node.js中的模块分为三种：</p>
<ul>
<li><p>内置模块</p>
</li>
<li><p>第三方模块</p>
</li>
<li><p>自定义模块</p>
</li>
</ul>
<p>下面简单介绍一下。</p>
<h3 id="1、内置模块"><a href="#1、内置模块" class="headerlink" title="1、内置模块"></a>1、内置模块</h3><pre class="highlight"><span class="line"><span class="keyword">const</span> process = <span class="built_in">require</span>(<span class="string">&#x27;process&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(process.<span class="property">version</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(path.<span class="title function_">resolve</span>(<span class="string">&#x27;../&#x27;</span>));</span><br></pre>

<p>require方法用于加载模块。</p>
<p>常见的内置模块包括：</p>
<ul>
<li><p>FS：文件系统模块</p>
</li>
<li><p>path：路径模块</p>
</li>
<li><p>OS：操作系统相关</p>
</li>
<li><p>net：网络相关</p>
</li>
<li><p>http</p>
</li>
<li><p>…</p>
</li>
</ul>
<p>你可能会有疑问：Node.js 这么牛吗？还能直接和操作系统做交互？</p>
<p>带着这个疑问，我们不妨简单看看 Node.js 的源码，以 os 模块举例：</p>
<ul>
<li><p>打开os模块的源码：<a target="_blank" rel="noopener" href="https://github.com/nodejs/node/blob/master/lib/os.js">https://github.com/nodejs/node/blob/master/lib/os.js</a>，翻到最底部，找到 <code>cpus</code>这个方法</p>
</li>
<li><p>进而找到 <code>getCPUs()</code></p>
</li>
<li><p>internalBinding(‘os’)：通过 internalBinding 可以调用系统底层的方法。internalBinding 主要是 JS 虚拟机在做的事情。</p>
</li>
<li><p><code>internalBinding(&#39;os&#39;)</code> 的实现，在 <a target="_blank" rel="noopener" href="https://github.com/nodejs/node/blob/master/src/node_os.cc">https://github.com/nodejs/node/blob/master/src/node_os.cc</a> 里，里面都是 C++ 的代码。比如有一个<code>getCPUs</code>方法。</p>
</li>
</ul>
<p>现在你知道了，JS本身是没有能力获取底层系统资源的，这一切都是 JS虚拟机在和底层做交互，然后通过 JS 的表现形式，暴露给应用层。</p>
<p>另外，还有很多库，是直接使用C&#x2F;++编写的，通过编译之后，再提供给 JS 应用层调用，或者直接提供给 Node.js层使用。</p>
<p>**所有的编程语言底层都会回归C&#x2F;C++**，甚至是汇编语言。</p>
<h3 id="2、require-加载第三方包的机制"><a href="#2、require-加载第三方包的机制" class="headerlink" title="2、require 加载第三方包的机制"></a>2、require 加载第三方包的机制</h3><pre class="highlight"><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br></pre>

<p>require 加载第三方包的机制：</p>
<p>（1）第三方包安装好后，这个包一般会存放在当前项目的 node_modules 文件夹中。我们找到这个包的 package.json 文件，并且找到里面的main属性对应的入口模块，这个入口模块就是这个包的入口文件。</p>
<p>（2）如果第三方包中没有找到package.json文件，或者package.json文件中没有main属性，则默认加载第三方包中的index.js文件。</p>
<p>（3）如果在 node_modules 文件夹中没有找到这个包，或者以上所有情况都没有找到，则会向上一级父级目录下查找node_modules文件夹，查找规则如上一致。</p>
<p>（4）如果一直找到该模块的磁盘根路径都没有找到，则会报错：can not find module xxx。</p>
<h3 id="3、自定义模块（module）："><a href="#3、自定义模块（module）：" class="headerlink" title="3、自定义模块（module）："></a>3、自定义模块（module）：</h3><p>每个文件就是一个模块，有自己的作用域。在一个文件里面定义的变量、函数、类，都是私有的，对其他文件不可见。</p>
<p>举例：</p>
<pre class="highlight"><span class="line">var example = require(&#x27;./example.js&#x27;);</span><br><span class="line">console.log(example.x); // 5</span><br><span class="line">console.log(example.addX(1)); // 6</span><br></pre>

<h2 id="读取文件"><a href="#读取文件" class="headerlink" title="读取文件"></a>读取文件</h2><p>今天这篇文章，重点讲一下 Node 内置模块中的 <strong>fs（文件处理模块）</strong>。</p>
<p>在使用文件模块之前，记得先导入：</p>
<pre class="highlight"><span class="line"><span class="comment">// 导入文件模块</span></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br></pre>

<p>fs 的英文全称是 File System。fs 模块提供了很多 api 方法，我们首先应该学习的方法是<strong>文件读取</strong>。</p>
<p>Node中文件读取的方式主要有以下几种。</p>
<h3 id="异步读取文件-fs-readFile"><a href="#异步读取文件-fs-readFile" class="headerlink" title="异步读取文件 fs.readFile()"></a>异步读取文件 fs.readFile()</h3><p>语法格式：</p>
<pre class="highlight"><span class="line">fs.<span class="title function_">readFile</span>(file[, options], <span class="title function_">callback</span>(error, data))</span><br></pre>

<p>代码举例：</p>
<pre class="highlight"><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"></span><br><span class="line">fs.<span class="title function_">readFile</span>(<span class="string">&#x27;hello.txt&#x27;</span>, <span class="string">&#x27;utf8&#x27;</span>, <span class="function">(<span class="params">err, data</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) &#123;</span><br><span class="line">        <span class="comment">// 失败</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(err)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 成功</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;异步读取数据：&#x27;</span> + data2)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre>


<p>如果需要嵌套读取多个文件，可以用 promise 或者 async … await 进行封装。代码举例如下。</p>
<h3 id="promise-封装-fs-readFile"><a href="#promise-封装-fs-readFile" class="headerlink" title="promise 封装 fs.readFile()"></a>promise 封装 fs.readFile()</h3><pre class="highlight"><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">fsRead</span>(<span class="params">path</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        fs.<span class="title function_">readFile</span>(path, &#123; <span class="attr">flag</span>: <span class="string">&#x27;r&#x27;</span>, <span class="attr">encoding</span>: <span class="string">&quot;utf-8&quot;</span> &#125;, <span class="function">(<span class="params">err, data</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (err) &#123;</span><br><span class="line">                <span class="comment">//失败执行的内容</span></span><br><span class="line">                <span class="title function_">reject</span>(err)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">//成功执行的内容</span></span><br><span class="line">                <span class="title function_">resolve</span>(data)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> promise1 = <span class="title function_">fsRead</span>(<span class="string">&#x27;hello1.txt&#x27;</span>)</span><br><span class="line">promise1.<span class="title function_">then</span>(<span class="function"><span class="params">res1</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res1);</span><br><span class="line">    <span class="keyword">return</span> <span class="title function_">fsRead</span>(<span class="string">&#x27;hello2.txt&#x27;</span>);</span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="function"><span class="params">res2</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res2);</span><br><span class="line">    <span class="keyword">return</span> <span class="title function_">fsRead</span>(<span class="string">&#x27;hello3.txt&#x27;</span>);</span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="function"><span class="params">res3</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre>

<h3 id="async-…-await-封装-fs-readFile"><a href="#async-…-await-封装-fs-readFile" class="headerlink" title="async … await 封装 fs.readFile()"></a>async … await 封装 fs.readFile()</h3><p>这个写法更为简洁，推荐。</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">fsRead</span>(<span class="params">path</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        fs.<span class="title function_">readFile</span>(path, &#123; <span class="attr">flag</span>: <span class="string">&#x27;r&#x27;</span>, <span class="attr">encoding</span>: <span class="string">&quot;utf-8&quot;</span> &#125;, <span class="function">(<span class="params">err, data</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (err) &#123;</span><br><span class="line">                <span class="comment">//失败执行的内容</span></span><br><span class="line">                <span class="title function_">reject</span>(err)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">//成功执行的内容</span></span><br><span class="line">                <span class="title function_">resolve</span>(data)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">ReadList</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> res1 = <span class="keyword">await</span> <span class="title function_">fsRead</span>(<span class="string">&#x27;hello1.txt&#x27;</span>);</span><br><span class="line">    <span class="keyword">var</span> res2 = <span class="keyword">await</span> <span class="title function_">fsRead</span>(<span class="string">&#x27;hello2.txt&#x27;</span>);</span><br><span class="line">    <span class="keyword">var</span> res3 = <span class="keyword">await</span> <span class="title function_">fsRead</span>(<span class="string">&#x27;hello3.txt&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 执行方法</span></span><br><span class="line"><span class="title class_">ReadList</span>();</span><br><span class="line"></span><br></pre>


<h3 id="同步读取文件-fs-readFileSync"><a href="#同步读取文件-fs-readFileSync" class="headerlink" title="同步读取文件 fs.readFileSync()"></a>同步读取文件 fs.readFileSync()</h3><p>语法格式：</p>
<pre class="highlight"><span class="line">fs.<span class="title function_">readFileSync</span>(file[, options])</span><br></pre>

<p>代码举例：</p>
<pre class="highlight"><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> data = fs.<span class="title function_">readFileSync</span>(<span class="string">&#x27;hello.txt&#x27;</span>, <span class="string">&#x27;utf8&#x27;</span>);</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(data);</span><br><span class="line">&#125; <span class="keyword">catch</span>(e) &#123;</span><br><span class="line">  <span class="comment">// 文件不存在，或者权限错误</span></span><br><span class="line">  <span class="keyword">throw</span> e;</span><br><span class="line">&#125;</span><br></pre>

<h3 id="Node-js-中的同步和异步的区别"><a href="#Node-js-中的同步和异步的区别" class="headerlink" title="Node.js 中的同步和异步的区别"></a>Node.js 中的同步和异步的区别</h3><p>fs模块对文件的几乎所有操作都有同步和异步两种形式。例如：readFile() 和 readFileSync()。</p>
<p>区别：</p>
<ul>
<li><p>同步调用会阻塞代码的执行，异步则不会。</p>
</li>
<li><p>异步调用会将 读取任务 下达到任务队列，直到任务执行完成才会回调。</p>
</li>
<li><p>异常处理方面：同步必须使用 try catch 方式，异步可以通过回调函数的第一个参数。【重要】</p>
</li>
</ul>
<h2 id="写入文件"><a href="#写入文件" class="headerlink" title="写入文件"></a>写入文件</h2><p>语法格式：</p>
<pre class="highlight"><span class="line">fs.<span class="title function_">write</span>(fd, string[, position[, encoding]], callback)</span><br><span class="line"></span><br></pre>

<p>async … await 封装：</p>
<pre class="highlight"><span class="line"><span class="keyword">let</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">writeFs</span>(<span class="params">path, content</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">        fs.<span class="title function_">writeFile</span>(path, content, &#123; <span class="attr">flag</span>: <span class="string">&quot;a&quot;</span>, <span class="attr">encoding</span>: <span class="string">&quot;utf-8&quot;</span> &#125;, <span class="keyword">function</span> (<span class="params">err</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (err) &#123;</span><br><span class="line">                <span class="comment">//console.log(&quot;写入内容出错&quot;)</span></span><br><span class="line">                <span class="title function_">reject</span>(err)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="title function_">resolve</span>(err)</span><br><span class="line">                <span class="comment">//console.log(&quot;写入内容成功&quot;)</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">writeList</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">await</span> <span class="title function_">writeFs</span>(<span class="string">&#x27;1.html&#x27;</span>, <span class="string">&quot;&lt;h1&gt;qianguyihao&lt;/h1&gt;&quot;</span>);</span><br><span class="line">    <span class="keyword">await</span> <span class="title function_">writeFs</span>(<span class="string">&#x27;2.html&#x27;</span>, <span class="string">&quot;&lt;h1&gt;hello world&lt;/h1&gt;&quot;</span>);</span><br><span class="line">    <span class="keyword">await</span> <span class="title function_">writeFs</span>(<span class="string">&#x27;3.html&#x27;</span>, <span class="string">&quot;&lt;h1&gt;永不止步&lt;/h1&gt;&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title function_">writeList</span>()</span><br></pre>

<h2 id="删除文件"><a href="#删除文件" class="headerlink" title="删除文件"></a>删除文件</h2><p>语法格式：</p>
<pre class="highlight"><span class="line">fs.<span class="title function_">unlink</span>(path, callback)</span><br></pre>

<p>参数说明：</p>
<ul>
<li>path：文件路径。</li>
<li>callback：回调函数。</li>
</ul>
<p>代码举例：</p>
<pre class="highlight"><span class="line">fs.<span class="title function_">unlink</span>(<span class="string">&#x27;path/file.txt&#x27;</span>, <span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;文件删除成功&#x27;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br></pre>

<p>备注：<code>fs.unlink()</code> 不能用于删除目录。 如果要删除目录，可以使用 <code>fs.rmdir()</code>。</p>
<h2 id="Buffer"><a href="#Buffer" class="headerlink" title="Buffer"></a>Buffer</h2><p>通过 Buffer 开辟的内存空间，都是连续的内存空间，所以效率比较高。</p>
<p>代码举例1：</p>
<pre class="highlight"><span class="line"></span><br><span class="line"><span class="comment">// 将字符串转成 buffer 对象</span></span><br><span class="line"><span class="keyword">const</span> str = <span class="string">&#x27;qianguyihao&#x27;</span>;</span><br><span class="line"><span class="keyword">let</span> buffer = <span class="title class_">Buffer</span>.<span class="title function_">from</span>(str);</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(buffer); <span class="comment">// 输出16进制编码</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(buffer.<span class="title function_">toString</span>()); <span class="comment">// 输出字符串：qianguyihao</span></span><br></pre>

<p>代码举例2：</p>
<pre class="highlight"><span class="line"><span class="comment">// 从内存中开辟一个新的缓冲区</span></span><br><span class="line"><span class="keyword">let</span> buffer = <span class="title class_">Buffer</span>.<span class="title function_">alloc</span>(<span class="number">20</span>);</span><br><span class="line">buffer[<span class="number">0</span>] = <span class="string">&#x27;a&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(buffer);</span><br><span class="line"></span><br></pre>


<h2 id="读取目录"><a href="#读取目录" class="headerlink" title="读取目录"></a>读取目录</h2><p>语法格式：</p>
<pre class="highlight"><span class="line">fs.<span class="title function_">mkdir</span>(path[, options], callback)</span><br></pre>

<p>参数说明：</p>
<ul>
<li><p>path：文件路径。</p>
</li>
<li><p>options参数可以是：</p>
<ul>
<li>recursive：是否以递归的方式创建目录，默认为 false。</li>
<li>mode：设置目录权限，默认为 0777。</li>
</ul>
</li>
</ul>
<p>代码举例：</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">&quot;fs&quot;</span>);</span><br><span class="line">​</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;查看 /tmp 目录&quot;</span>);</span><br><span class="line">fs.<span class="title function_">readdir</span>(<span class="string">&quot;/tmp/&quot;</span>,<span class="keyword">function</span>(<span class="params">err, files</span>)&#123;</span><br><span class="line">   <span class="keyword">if</span> (err) &#123;</span><br><span class="line">       <span class="keyword">return</span> <span class="variable language_">console</span>.<span class="title function_">error</span>(err);</span><br><span class="line">   &#125;</span><br><span class="line">   files.<span class="title function_">forEach</span>( <span class="keyword">function</span> (<span class="params">file</span>)&#123;</span><br><span class="line">       <span class="variable language_">console</span>.<span class="title function_">log</span>( file );</span><br><span class="line">   &#125;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br></pre>


<p>其他的还有：（暂略）</p>
<ul>
<li><p>删除目录</p>
</li>
<li><p>输入输出</p>
</li>
</ul>

  </div>
  <div>
    
      <div 
        class="post-note note-warning copyright" 
        style="margin-top: 42px">
        <p>
          <span style="font-weight: bold;">作者：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="/about">
            zwl5670
          </a>
        </p>
        <p>
          <span style="font-weight: bold;">文章链接：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="https://zwl5670.gitee.io/2011/08/01/11-Node.js/05-Node.js%E5%86%85%E7%BD%AE%E6%A8%A1%E5%9D%97%EF%BC%9Afs%E6%96%87%E4%BB%B6%E6%A8%A1%E5%9D%97/">
            https://zwl5670.gitee.io/2011/08/01/11-Node.js/05-Node.js%E5%86%85%E7%BD%AE%E6%A8%A1%E5%9D%97%EF%BC%9Afs%E6%96%87%E4%BB%B6%E6%A8%A1%E5%9D%97/
          </a>
        </p>
        <p><span style="font-weight: bold;">版权声明：</span>本博客所有文章除特别声明外，均采用<a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0 协议</a>。转载请注明出处！</p>
      </div>
    
  </div>
</article>
<div class="nav">
  
    <div class="nav-item-prev">
      <a 
        href="/2011/08/01/11-Node.js/04-Node.js%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83%EF%BC%9ACommonJS/" 
        class="nav-link">
        <i class="iconfont icon-left nav-prev-icon"></i>
        <div>
          <div class="nav-label">上一篇</div>
          
            <div class="nav-title">04-Node.js模块化规范：CommonJS </div>
          
        </div>
      </a>
    </div>
  
  
    <div class="nav-item-next">
      <a 
        href="/2011/08/01/11-Node.js/06-Node.js%E5%86%85%E7%BD%AE%E6%A8%A1%E5%9D%97%EF%BC%9Apath%E8%B7%AF%E5%BE%84%E6%A8%A1%E5%9D%97/" 
        class="nav-link">
        <div>
          <div class="nav-label">下一篇</div>
          
            <div class="nav-title">06-Node.js内置模块：path路径模块 </div>
          
        </div>
        <i class="iconfont icon-right nav-next-icon"></i>
      </a>
    </div>
  
</div>

<div 
  class="card card-content toc-card" 
  id="mobiletoc">
  <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Node-js-%E7%9A%84%E5%AE%98%E6%96%B9API%E6%96%87%E6%A1%A3"><span class="toc-text">Node.js 的官方API文档</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Node-js-%E4%B8%AD%E6%A8%A1%E5%9D%97%E7%9A%84%E5%88%86%E7%B1%BB"><span class="toc-text">Node.js 中模块的分类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%86%85%E7%BD%AE%E6%A8%A1%E5%9D%97"><span class="toc-text">1、内置模块</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81require-%E5%8A%A0%E8%BD%BD%E7%AC%AC%E4%B8%89%E6%96%B9%E5%8C%85%E7%9A%84%E6%9C%BA%E5%88%B6"><span class="toc-text">2、require 加载第三方包的机制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E6%A8%A1%E5%9D%97%EF%BC%88module%EF%BC%89%EF%BC%9A"><span class="toc-text">3、自定义模块（module）：</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6"><span class="toc-text">读取文件</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6-fs-readFile"><span class="toc-text">异步读取文件 fs.readFile()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#promise-%E5%B0%81%E8%A3%85-fs-readFile"><span class="toc-text">promise 封装 fs.readFile()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#async-%E2%80%A6-await-%E5%B0%81%E8%A3%85-fs-readFile"><span class="toc-text">async … await 封装 fs.readFile()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6-fs-readFileSync"><span class="toc-text">同步读取文件 fs.readFileSync()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Node-js-%E4%B8%AD%E7%9A%84%E5%90%8C%E6%AD%A5%E5%92%8C%E5%BC%82%E6%AD%A5%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-text">Node.js 中的同步和异步的区别</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%99%E5%85%A5%E6%96%87%E4%BB%B6"><span class="toc-text">写入文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E6%96%87%E4%BB%B6"><span class="toc-text">删除文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Buffer"><span class="toc-text">Buffer</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%BB%E5%8F%96%E7%9B%AE%E5%BD%95"><span class="toc-text">读取目录</span></a></li></ol>
</div>
            </main>
            <aside class="right-column">
              <div class="sticky-widescreen">
  
  
    <article class="card card-content toc-card">
      <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Node-js-%E7%9A%84%E5%AE%98%E6%96%B9API%E6%96%87%E6%A1%A3"><span class="toc-text">Node.js 的官方API文档</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Node-js-%E4%B8%AD%E6%A8%A1%E5%9D%97%E7%9A%84%E5%88%86%E7%B1%BB"><span class="toc-text">Node.js 中模块的分类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%86%85%E7%BD%AE%E6%A8%A1%E5%9D%97"><span class="toc-text">1、内置模块</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81require-%E5%8A%A0%E8%BD%BD%E7%AC%AC%E4%B8%89%E6%96%B9%E5%8C%85%E7%9A%84%E6%9C%BA%E5%88%B6"><span class="toc-text">2、require 加载第三方包的机制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E6%A8%A1%E5%9D%97%EF%BC%88module%EF%BC%89%EF%BC%9A"><span class="toc-text">3、自定义模块（module）：</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6"><span class="toc-text">读取文件</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6-fs-readFile"><span class="toc-text">异步读取文件 fs.readFile()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#promise-%E5%B0%81%E8%A3%85-fs-readFile"><span class="toc-text">promise 封装 fs.readFile()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#async-%E2%80%A6-await-%E5%B0%81%E8%A3%85-fs-readFile"><span class="toc-text">async … await 封装 fs.readFile()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6-fs-readFileSync"><span class="toc-text">同步读取文件 fs.readFileSync()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Node-js-%E4%B8%AD%E7%9A%84%E5%90%8C%E6%AD%A5%E5%92%8C%E5%BC%82%E6%AD%A5%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-text">Node.js 中的同步和异步的区别</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%99%E5%85%A5%E6%96%87%E4%BB%B6"><span class="toc-text">写入文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E6%96%87%E4%BB%B6"><span class="toc-text">删除文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Buffer"><span class="toc-text">Buffer</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%BB%E5%8F%96%E7%9B%AE%E5%BD%95"><span class="toc-text">读取目录</span></a></li></ol>
    </article>
  
  
  <article class="card card-content">
    <div class="recent-posts-card">
  <div class="recent-posts-header">
    <i 
      class="iconfont icon-wenzhang_huaban" 
      style="padding-right: 2px;">
    </i>最近文章
  </div>
  <div class="recent-posts-list">
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/11-React%20Navive%E5%88%9D%E8%AF%86/"><div class="recent-posts-item-content">11-React Navive初识</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/10-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E4%BD%BF%E7%94%A8customRequest%E6%96%B9%E6%B3%95%E8%87%AA%E5%AE%9A%E4%B9%89%E4%B8%8A%E4%BC%A0%E8%A1%8C%E4%B8%BA/"><div class="recent-posts-item-content">10-AntD框架的upload组件上传图片时使用customRequest方法自定义上传行为</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/09-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E9%81%87%E5%88%B0%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91/"><div class="recent-posts-item-content">09-AntD框架的upload组件上传图片时遇到的一些坑</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/08-Ant%20Design%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/"><div class="recent-posts-item-content">08-Ant Design的基本使用</div></a>
      </div>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
          </div>
        </div>
      </div>
    </div>
     
    <footer class="footer">
  <div class="footer-container">
    <div>
      <div class="footer-dsc">
        <span>
          Copyright ©
          
            2023
          
          
        </span>
        &nbsp;
        <a 
          href="/" 
          class="footer-link">
          前端面试
        </a>
      </div>
    </div>

    
      <div class="footer-dsc">
        
          Powered by
          <a 
            href="https://hexo.io/" 
            class="footer-link" 
            target="_blank" 
            rel="nofollow noopener noreferrer">
            &nbsp;Hexo
          </a>
        
        
          <span>&nbsp;|&nbsp;</span>
        
        
          Theme -
          <a 
            href="https://github.com/theme-kaze" 
            class="footer-link" 
            target="_blank"
            rel="nofollow noopener noreferrer">
            &nbsp;Kaze
          </a>
        
      </div>
    
    
    
    
</footer>
 
    
  <a 
    role="button" 
    id="scrollbutton" 
    class="basebutton" 
    aria-label="回到顶部">
    <i class="iconfont icon-arrowleft button-icon"></i>
  </a>

<a 
  role="button" 
  id="menubutton"
  aria-label="menu button"
  class="basebutton">
  <i class="iconfont icon-menu button-icon"></i>
</a>
<a 
  role="button" 
  id="popbutton" 
  class="basebutton" 
  aria-label="控制中心">
  <i class="iconfont icon-expand button-icon"></i>
</a>
<a 
  role="button" 
  id="darkbutton" 
  class="basebutton darkwidget" 
  aria-label="夜色模式">
  <i class="iconfont icon-weather button-icon"></i>
</a>
<a 
  role="button" 
  id="searchbutton" 
  class="basebutton searchwidget" 
  aria-label="搜索">
  <i class="iconfont icon-search button-icon"></i>
</a> 
     
     
     
      <script>
  var addImgLayout = function () {
    var img = document.querySelectorAll('.post-content img')
    var i
    for (i = 0; i < img.length; i++) {
      var wrapper = document.createElement('a')
      wrapper.setAttribute('href', img[i].getAttribute('data-src'))
      wrapper.setAttribute('aria-label', 'illustration')
      wrapper.style.cssText =
        'width: 100%; display: flex; justify-content: center;'
      if (img[i].alt) wrapper.dataset.caption = img[i].alt
      wrapper.dataset.nolink = true
      img[i].before(wrapper)
      wrapper.append(img[i])
      var divWrap = document.createElement('div')
      divWrap.classList.add('gallery')
      wrapper.before(divWrap)
      divWrap.append(wrapper)
    }
    baguetteBox.run('.gallery')
  }
</script>
<script>
  loadScript(
    "/js/lib/lightbox/baguetteBox.min.js",
    addImgLayout
  )
</script>
 
     
     
    <script src="/js/main.js"></script> 
     
    
      <script>
        var addLazyload = function () {
          var observer = lozad('.lozad', {
            load: function (el) {
              el.srcset = el.getAttribute('data-src')
            },
            loaded: function (el) {
              el.classList.add('loaded')
            },
          })
          observer.observe()
        }
      </script>
      <script>
        loadScript('/js/lib/lozad.min.js', addLazyload)
      </script>
    
    <script src="//instant.page/5.1.0" type="module"
      integrity="sha384-by67kQnR+pyfy8yWP4kPO12fHKRLHZPfEsiSXR8u2IKcTdxD805MGUXBzVPnkLHw"></script>
    
    
  </body>
</html>
